package com.youxin.chat.basic.controller;



import com.youxin.base.TResult;
import com.youxin.chat.basic.service.SysFileService;
import com.youxin.chat.basic.config.YouxinProperties;
import com.youxin.chat.basic.dto.file.FileDto;
import com.youxin.user.annotation.LoginUser;
import com.youxin.user.model.SysUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@Api(value="文件相关", tags={"文件接口"})
@Controller
@RequestMapping("file")
public class FileController {

    private static final Logger logger = LoggerFactory.getLogger(FileController.class);
    @Resource
    private SysFileService sysFileService;

    @Resource
    private ResourceLoader resourceLoader;

    @Resource
    private YouxinProperties youxinProperties;

    @ApiOperation("上传文件")
    @PostMapping("upload")
    @ResponseBody
    public TResult<String> uploadFile(@RequestParam("file") MultipartFile file, @RequestParam(value = "type",defaultValue = "0")Integer type, @LoginUser SysUser sysUser) {
        String fileId =  sysFileService.saveFile(file,type,sysUser.getUserNo());
        return TResult.success(fileId);
    }

    @ApiOperation("下载文件")
    @GetMapping("download/{id}")
    @ResponseBody
    public void download(@PathVariable String id, HttpServletResponse response) {
        FileDto fileDto = sysFileService.download(id);

        response.setContentType("application/force-download");// 设置强制下载不打开
        response.addHeader("Content-Disposition",
                "attachment;fileName=" + fileDto.getFileName());// 设置文件名
        byte[] buffer = new byte[1024];
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        try {
            fis = new FileInputStream(new File(fileDto.getFilePath()));
            bis = new BufferedInputStream(fis);
            OutputStream os = response.getOutputStream();
            int i = bis.read(buffer);
            while (i != -1) {
                os.write(buffer, 0, i);
                i = bis.read(buffer);
            }
        } catch (Exception e) {
            logger.error("下载文件出错", e);
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    logger.error("关闭流出错", e);
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    logger.error("关闭流出错", e);
                }
            }

        }
    }
}
